<template>
  <div class="image_upload">
    <label class="select_file" for="fileInput">选择文件
      <input class="file_input" multiple id="fileInput" ref="fileInput" type="file" @change="handleChange"/></label>
    <el-button type="primary" @click="handleUpload">上传</el-button>
    <img v-for="(item, index) in imgList" :src="item.src" :key="index">
  </div>
</template>

<script>
  import md5 from "md5"

  export default {
    components: {},
    data () {
      return {
        imgList: []
      }
    },
    methods: {
      handleChange (e) {
        this.setData(e.target.files);
      },
      setData (files) {
        Array.from(files).forEach(file => {
          const obj = {
            src: "",
            file: file,
            size: file.size,
            name: md5(file.name) + "." + (file.type.slice(6)),
            txt: "未上传"
          };
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.addEventListener("load", e => {
            obj.src = e.target.result;
          });

          this.checkFileLoaded(obj);
          this.imgList.push(obj);
        });
      },
      checkFileLoaded (obj) {
        const percent = localStorage.getItem("percent_" + obj.name);
        if (percent && Number(percent) !== 100) {
          obj.txt = "已上传：" + percent + "%";
        }
      },
      handleUpload () {
        this.imgList.forEach((item, index) => {
          this.uploadFn(item, index, true);
        });
      },
      uploadFn (item, index, isFirstUpload) {
        const file = item.file;
        const fileName = item.name;
        let chunk = Number(localStorage.getItem("chunk_" + fileName));
        const totalSize = item.size;
        const chunkSize = 1024;
        const chunks = Math.ceil(totalSize / chunkSize);
        const isLastChunk = (chunk === chunks - 1);

        const chunkBegin = chunk * chunkSize;
        const chunkEnd = (chunk + 1) * chunkSize > totalSize ? totalSize : (chunk + 1) * chunkSize;
        const percent = (100 * chunkEnd / totalSize).toFixed(1);

        const formData = new FormData();
        formData.append("isFirstUpload", !!isFirstUpload);
        formData.append("currentChunk", file.slice(chunkBegin, chunkEnd));
        formData.append("fileName", fileName);
        formData.append("totalSize", totalSize);
        formData.append("isLastChunk", isLastChunk);

        this.$.ajax({
          type: "post",
          url: "/api/info",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data"
          },
          success: (data) => {
            localStorage.setItem("percent_" + fileName, percent);
            item.txt = "已上传：" + percent + "%";
            if (chunk === chunks - 1) {
              item.txt = "已完成";

              this.imgList.splice(this.imgList.indexOf(item), 1);
              if (!this.imgList.length) {
                this.$message({
                  type: "success",
                  message: "上传成功！"
                });

                this.$refs.fileInput.value = "";
              }
              localStorage.removeItem("percent_" + fileName);
              localStorage.removeItem("chunk_" + fileName);
            } else {
              localStorage.setItem("chunk_" + fileName, ++chunk);
              this.uploadFn(item, index);
            }
          },
          error () {
            item.txt = "上传失败";
          }
        })
      },
      handleError (e) {
//        e.target.src = require("../assets/head.png");
      }
    }
  }
</script>

<style lang="scss">
  .image_upload {
    .select_file {
      display: inline-block;
      padding: 0 10px;
      background-color: #0bb20c;
      text-align: center;
      color: #fff;
      font-size: 13px;
      line-height: 2.3;
      border-radius: 5px;
    }

    .file_input {
      display: none;
    }

    .image_grid {
      text-align: center;

      &::before, &::after {
        display: none;
      }
    }

    img {
      width: 80px;
      height: 80px;
    }

    .progress {
      text-align: center;
      color: #333333;
      font-size: 12px;
    }

    .weui-grid::before, .weui-grid::after {
      display: none;
    }
  }
</style>
